package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import component.Data;
import dao.UserDao;
import domain.User;
import impl.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 */
@WebServlet("/test")
public class TestServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setSex(sex);
        UserDao userDao = new UserDaoImpl();
        userDao.addUser(user);
        User resultUser = userDao.selectUser(2);
        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write(resultUser.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String body = Data.readBody(req);
        User user = objectMapper.readValue(body, User.class);
        UserDao userDao = new UserDaoImpl();
        userDao.addUser(user);
        List<User> users = userDao.getUserList();
        resp.setContentType("application/json; charset=utf8");
        String respJackson = objectMapper.writeValueAsString(users);
        resp.getWriter().write(respJackson);
    }
}
